<template>
    <div class="task-dialog">
        <el-dialog v-model="dialogFormVisible" title="运营文章编排" width="500" @close="handleCancel">
            <div style="padding: 10px;">
                <el-form :model="taskForm" ref="taskFormRef" :rules="rules" label-width="auto">
                    <el-form-item label="文章分类：" prop="article_category_id">
                        <el-cascader style="width: 250px;margin-right: 10px;" clearable filterable
                            v-model="taskForm.article_category_id" :options="categoryOptions" :props="categoryProps"
                            placeholder="请选择文章分类" />
                    </el-form-item>
                    <el-form-item label="文章数量：" prop="num">
                        <el-input v-model="taskForm.num" placeholder="请输入文章数量" style="width: 250px" type="number"
                            clearable />
                    </el-form-item>
                    <el-form-item label="账户" prop="accountId">
                        <el-select v-model="taskForm.accountId" placeholder="请选择账户名称" style="width: 250px" clearable
                            @change="handleSelectAccount">
                            <el-option v-for="item in accountNameOptions" :key="item.id" :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="网站" prop="site_id">
                        <el-select v-model="taskForm.site_id" placeholder="请选择所属网站" style="width: 250px" clearable
                            filterable>
                            <el-option v-for="item in siteOptions" :key="item.siteName" :label="item.siteName"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="语言" prop="lang_id">
                        <el-select v-model="taskForm.lang_id" placeholder="请选择语言" style="width: 250px" clearable
                            filterable>
                            <el-option v-for="item in languageOptions" :key="item.id" :label="item.langName"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="地区" prop="area">
                        <el-select v-model="taskForm.area" placeholder="请选择面向地区" style="width: 250px" clearable
                            filterable>
                            <el-option v-for="item in countryOptions" :key="item.label" :label="item.label"
                                :value="item.label" />
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="handleSubmit(taskFormRef)" :loading="isSubmitting"
                        :disabled="isSubmitting">
                        提交
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { defineComponent, reactive, ref } from 'vue';
import { useAuthStore } from '../store/auth';
import service from '../config';
import axios from 'axios';
import { countryOptions } from '../tool';
import { getDevModel } from '../config/EnvConfig';
defineComponent({ name: 'TaskConfiguration' })
const dialogFormVisible = ref(false)
const taskFormRef = ref<FormInstance>()
const isSubmitting = ref(false)
const categoryProps = {
    checkStrictly: true,
}
const options = ref([])
const categoryOptions = ref([])
const languageOptions = ref([])
const siteOptions = ref([])
const allSiteOptions = ref([])
const accountNameOptions = ref([])
const authStore = useAuthStore()
interface RuleForm {
    article_category_id: string[],
    num: number,
    topic: string,
    lang_id: number,
    site_id: number,
    accountId: number,
    area: string
}
const taskForm = ref<RuleForm>({
    article_category_id: [],
    num: null,
    topic: '',
    lang_id: null,
    site_id: null,
    accountId: null,
    area: ''
})


const rules = reactive<FormRules<RuleForm>>({
    article_category_id: [
        { required: true, message: '请选择文章分类', trigger: 'blur' },
    ],
    num: [
        { required: true, message: '请输入数量', trigger: 'blur' },
    ],
    lang_id: [{ required: true, message: '请选择语言', trigger: 'blur' }],
    site_id: [{ required: true, message: '请选择所属网站', trigger: 'blur' }],
    accountId: [{ required: true, message: '请选择账户名称', trigger: 'blur' }],
})

const openModal = (rowData?: any) => {
    dialogFormVisible.value = true
    if (categoryOptions.value?.length == 0 || languageOptions.value?.length == 0 || siteOptions.value?.length == 0 || accountNameOptions.value?.length == 0) {
        getArticleCategory()
        getlangCategory()
        getSite()
        getAccount()
    }

    // 回显数据
    if (rowData) {
        taskForm.value = {
            article_category_id: rowData.articleCategoryId,
            num: rowData.articleCount || null,
            topic: '',
            lang_id: rowData.langId || null,
            site_id: rowData.siteId || null,
            accountId: rowData.accountId || null,
            area: rowData.area || ''
        }
    }
}
const handleCancel = () => {
    dialogFormVisible.value = false
    taskForm.value = {
        article_category_id: null,
        num: null,
        topic: '',
        lang_id: null,
        site_id: null,
        accountId: null,
        area: ''
    }
}
const handleSelectAccount = () => {
    const selectedAccountId = taskForm.value.accountId
    if (selectedAccountId === null || selectedAccountId === undefined) {
        siteOptions.value = [...allSiteOptions.value]
        return
    }
    const filtered = allSiteOptions.value?.filter((item: any) => item.accountId == selectedAccountId) || []
    siteOptions.value = filtered
    const exists = filtered?.some((s: any) => s.id == taskForm.value.site_id)
    if (!exists) {
        taskForm.value.site_id = null
    }
}

const getAccount = () => {
    service.get('/account/getAll')
        .then(response => {
            accountNameOptions.value = response?.data
            accountNameOptions.value.push({ id: -1, name: '其他' })
        })
        .catch(error => {
            ElMessage.error(error)
        });
}

const getSite = () => {
    service.get('/site/getAll')
        .then(response => {
            allSiteOptions.value = response?.data || []
            siteOptions.value = [...allSiteOptions.value]
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}

const getlangCategory = () => {
    service.get('/lang/getAll')
        .then(response => {
            languageOptions.value = response?.data
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}


const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    if (isSubmitting.value) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            isSubmitting.value = true
            const webhookUrl = import.meta.env.PROD
                ? 'https://pixeljet-n8n.com/webhook/8a4738f8-cf53-4268-920a-3f7cecd0f357'
                : '/wkfapi/webhook/8a4738f8-cf53-4268-920a-3f7cecd0f357'
            // 处理 article_category_id，确保获取正确的分类ID
            let finalCategoryId
            if (Array.isArray(taskForm.value.article_category_id)) {
                // 如果是数组，取最后一个（子级ID）
                finalCategoryId = taskForm.value.article_category_id[taskForm.value.article_category_id.length - 1]
            } else {
                // 如果是字符串或数字，直接使用
                finalCategoryId = taskForm.value.article_category_id
            }

            taskForm.value.topic = options.value.find(item => item.id === finalCategoryId)?.alias || ''
            const langName = languageOptions.value.find(item => item.id === taskForm.value.lang_id)?.langName || ''
            service.post('/arrangeRecord/add', { articleCategoryId: finalCategoryId, area: taskForm.value.area ? taskForm.value.area : '美国', articleCount: taskForm.value.num, langId: taskForm.value.lang_id, siteId: taskForm.value.site_id, insertType: 1, accountId: taskForm.value.accountId })
                .then(resp => {
                    axios.post(webhookUrl, { ...taskForm.value, arrange_id: resp?.data, article_category_id: finalCategoryId, area: taskForm.value.area ? taskForm.value.area : '美国', created_user_id: authStore?.userId, lang: langName, devModel: getDevModel() })
                        .then(resp => {
                            ElMessage.success('提交成功！')
                            handleCancel()
                        })
                        .catch(err => { ElMessage.error(err || err.message) })
                        .finally(() => { isSubmitting.value = false })
                })
                .catch(err => { ElMessage.error(err || err.message) })
                .finally(() => { isSubmitting.value = false })

        } else {

        }
    })
}
const buildTree = (nodes, parentId = null) => {
    return nodes
        .filter(node => node.parentId === parentId)
        .map(node => {
            const children = buildTree(nodes, node.value);
            return {
                ...node,
                ...(children.length > 0 ? { children } : {})
            };
        });
}
const getArticleCategory = () => {
    service.get('/article/allCategory')
        .then(response => {
            options.value = response.data || []
            const treeData = response.data?.map(item => ({
                label: item.name,
                value: item.id,
                parentId: item.parentId,
                alias: item.alias
            }));
            categoryOptions.value = buildTree(treeData);
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}

defineExpose({ openModal })
</script>

<style lang="scss">
.task-dialog {
    .el-dialog {
        padding: 20px;

        .el-dialog__title {
            font-weight: 700;
        }

        .el-dialog__footer {
            padding: 0;
        }
    }

    .el-form-item {
        margin-bottom: 20px;
    }

    .el-form-item__label {
        font-size: 14px;
        font-weight: 600;
    }
}
</style>